package rsj.api.loginAuth;

import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.base.ThinkException;
import com.rlyy.aibase.view.key.APIKey_Enum;
import common.util.BoxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rsj.api.user.BaseLink;
import rsj.log.ModuleEnum;
import rsj.log.OperationLog;
import rsj.log.OperationTypeEnum;
import rsj.service.UserInfoService;
import rsj.utils.AesRsjUtil;
import rsj.utils.RedisUtils;

import java.util.UUID;

import static rsj.util.RedisKeyFactory.wrapLoginKey;
@RestController
public class Login extends BaseLink {

//    private static final int SESSION_EXPIRE = 12 * 60 * 60;// 12个小时
    protected static final int SESSION_EXPIRE = 30 * 60;// 30分钟

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 输入：
     * "_data_":{
     * "User_Uname":"admin",
     * "User_Password":"123456"
     * }
     * 输出：
     *
     * @param in
     * @return
     * @throws ThinkException
     */
    @RequestMapping(value = "rsj_pub_sso_login")
    @OperationLog(description = "登录", logType = OperationTypeEnum.LOGIN, logModule = ModuleEnum.USER_MANAGEMENT)
    public Box executeLink(Box in) throws ThinkException {
        MapNode data = in.getMapNode("data");
        String tid = in.getNode("$tid");
        // 1.校验登录用户信息
        MapNode userInfo = userInfoService.getAndCheckUserInfo( data, tid);

        String userId = userInfo.getValue("User_Id");

        // 2.加密 uId + 生成的token Access_Token
        String accessToken = encryptAccessToken(userId);

        // 3.以加密之后的信息 写入redis 缓存半个小时
        putToRedis(wrapLoginKey(userId), accessToken);
        //MapNode mapNode = new MapNode();
        //mapNode.putNode("password_update_warning",updatePasswordWarning(user.getUserPwdUpdateTm()));
        logger.info("登录成功***************");
        return BoxUtil.successBox(in, "登录成功！").putNode(APIKey_Enum.SSO.getKey(), accessToken);

    }




    private void putToRedis(String userIdKey, String accessToken) {
        //JedisUtil.put(String.valueOf(userIdKey), new MapNode().putNode(String.valueOf(userIdKey), accessToken), tid);
        RedisUtils.set(String.valueOf(userIdKey), accessToken, SESSION_EXPIRE);

    }

    private String encryptAccessToken(String userId) {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String uIdAndToken = userId + ":" + token;
        logger.info("token::" + uIdAndToken);
        return AesRsjUtil.encrypt(uIdAndToken);
    }
}
